<template>

<div>
    <el-button type="primary" @click="form.dialogFormVisible=true">新增</el-button>
<el-button type="danger" @click="del(form.selectArray)">删除</el-button>
</div>


<el-table :data="goods" border style="width: 100%"  @selection-change="handleSelectionChange">

  <el-table-column type="selection" width="55" />
    <el-table-column prop="goodsId" label="序号" />
    <el-table-column prop="goodsName" label="商品名称" width="120" />
    <el-table-column prop="goodsMade" label="生产批次"  width="150" />
    <el-table-column prop="goodsMade" label="生产批次"  width="150" >
     <!-- 商品图 -->
      <template v-slot="scope">
        <el-image style="width: 100px; height: 100px" :src="scope.row.goodsImage" fit="cover" />
      </template>
    </el-table-column>
    <el-table-column prop="goodsDay" label="保质期(天)" width="120"/>
    <el-table-column prop="goodsItem" label="生产许可证号" width="120" />
    <el-table-column prop="goodsCompany" label="生产企业" width="150" />
    <el-table-column label="信息完善度" width="120">
        <template v-slot="scope">
            <span style="color: green;">100%</span>
        </template>
    </el-table-column>
   
    <el-table-column prop="createByName" label="创建人" />
    <el-table-column label="创建时间" width="200">
        <template v-slot="scope">
           {{scope.row.createTime.substring(0,19).replace('T',' ')}}
        </template>
    </el-table-column>
    <el-table-column label="修改人">
      <template v-slot="scope">
        <span v-if="scope.row.modifyByName==null">暂无</span>
        <span v-else>{{ scope.row.modifyByName }}</span>
      </template>
    </el-table-column>
    <el-table-column label="修改时间" width="200">
        <template v-slot="scope">
           <span v-if="scope.row.modifyTime==null">暂无</span>
           <span v-else>
           {{scope.row.modifyTime.substring(0,19).replace('T',' ')}}</span>
        </template>
    </el-table-column>
    <el-table-column label="操作"  fixed="right" width="260">
        <template #default="scope">
          <el-button link size="small" type="primary" @click="handleEdit(scope.row.goodsId)">
          详情
        </el-button>
        <el-button link size="small" @click="handleEdit(scope.row.goodsId)">
          修改
        </el-button>
        <el-button link size="small" @click="handleExport(scope.row.userId)">
          导出溯源码
        </el-button>
        <el-button
        link
          size="small"
          type="danger"
          @click="handleDelete( scope.row)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 添加 -->
  <el-dialog v-model="form.dialogFormVisible" title="添加信息" width="500">
    <el-form :model="form" ref="ruleFormRef"
    :rules="rules" >
      <el-form-item label="商品名称" prop="goodsName">
        <el-input v-model="form.goodsName" autocomplete="off" />
      </el-form-item>

      <el-form-item label="生产批次" prop="goodsMade">
        <el-input v-model="form.goodsMade" autocomplete="off" />
      </el-form-item>

      <el-form-item label="保质期(天)" prop="goodsDay">
        <el-input v-model="form.goodsDay" autocomplete="off" />
      </el-form-item>

      <el-form-item label="生产许可证号" prop="goodsItem">
        <el-input v-model="form.goodsItem" autocomplete="off" />
      </el-form-item>

      <el-form-item label="生产企业" prop="goodsCompany">
        <el-input v-model="form.goodsCompany" autocomplete="off" />
      </el-form-item>

      <el-form-item label="封面图" prop="goodsImage">
        <el-upload
    class="avatar-uploader"
    action="http://localhost:11836/FarmApp/Upload"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
   
  >
    <img v-if="form.goodsImage" :src="form.goodsImage" class="avatar" style="width: 50px;height: 50px;" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
      </el-form-item>
      
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 修改 -->
  <el-dialog v-model="updateform.dialogupdate" title="修改信息" width="500">
    <el-form :model="updateform" ref="ruleFormRef"
    :rules="rules" >
      <el-form-item label="商品名称" prop="goodsName">
        <el-input v-model="updateform.goodsName" autocomplete="off" />
      </el-form-item>

      <el-form-item label="生产批次" prop="goodsMade">
        <el-input v-model="updateform.goodsMade" autocomplete="off" />
      </el-form-item>

      <el-form-item label="保质期(天)" prop="goodsDay">
        <el-input v-model="updateform.goodsDay" autocomplete="off" />
      </el-form-item>

      <el-form-item label="生产许可证号" prop="goodsItem">
        <el-input v-model="updateform.goodsItem" autocomplete="off" />
      </el-form-item>

      <el-form-item label="生产企业" prop="goodsCompany">
        <el-input v-model="updateform.goodsCompany" autocomplete="off" />
      </el-form-item>

      <el-form-item label="封面图" prop="goodsImage">
        <el-upload
    class="avatar-uploader"
    action="http://localhost:11836/FarmApp/Upload"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
   
  >
    <img v-if="updateform.goodsImage" :src="updateform.goodsImage" class="avatar" style="width: 50px;height: 50px;" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
      </el-form-item>
      
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="goodsUpdate(ruleFormRef)">保存</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 导出 -->
  <el-dialog v-model="exportform.ExportdialogFormVisible" title="导出信息" width="500">
    <el-form :model="form">
      <el-form-item label="导出数量">
        <el-input v-model="exportform.num" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="ExportData()">导出</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 分页 -->
  <div>
    <table>
      <tbody>
        <tr>
          <td>
            <el-pagination
      v-model:current-page="form.pageIndex"
      v-model:page-size="form.pageSize"
      :page-sizes="[2, 3, 4, 5]"
      prev-text="上一页"
      next-text="下一页"
      :background="true"
      layout="total,slot"
      :total="form.recordCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
  ,每页{{ form.pageSize }}条,{{ form.pageIndex }}/{{ form.pageCount }}
    </el-pagination> 
          </td>
          <td>
            <el-pagination
      v-model:current-page="form.pageIndex"
      v-model:page-size="form.pageSize"
      :page-sizes="[2, 3, 4, 5]"
      prev-text="上一页"
      next-text="下一页"
      :background="true"
      layout="slot, prev, pager, next"
      :total="form.recordCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
  <el-button @click="handleCurrentChange(1)" :disabled="form.pageIndex==1">首页</el-button>
    </el-pagination> 
          </td>
          <td>
            <el-pagination
      v-model:current-page="form.pageIndex"
      v-model:page-size="form.pageSize"
      :page-sizes="[2, 3, 4, 5]"
      prev-text="上一页"
      next-text="下一页"
      :background="true"
      layout="slot, jumper,sizes"
      :total="form.recordCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
  <el-button @click="handleCurrentChange(form.pageCount)" :disabled="form.pageIndex==form.pageCount">尾页</el-button>
    </el-pagination> 
          </td>
        </tr>
      </tbody>
    </table>
  </div>

   
    
    
</template>
    
    <script setup lang="ts">
    
    import { ElMessage,ElMessageBox } from 'element-plus';
    import {ref,reactive,onMounted} from 'vue'
    import {useRouter} from 'vue-router'
    const router=useRouter()
    import axios from 'axios'
    import type { FormInstance } from 'element-plus'
    import Cookie from 'cookies-ts'
    const cookie=new Cookie()
    const ruleFormRef = ref<FormInstance>()
    import {useCounterStore} from '../stores/counter'
    const store=useCounterStore()

        import { Plus } from '@element-plus/icons-vue'
        //添加
    const form=reactive({
      userId:store.$state.userId,
      createById:store.$state.userId,
      createByName:store.$state.userNickname,
      goodsName:'',
      goodsMade:'',
      goodsDay:'',
      goodsItem:'',
      goodsCompany:'',
      goodsImage:'',
      dialogFormVisible:false,
      selectArray:[],
      pageIndex:1,
      pageSize:3,
      recordCount:'',
      pageCount:''
      
    })
    //修改
    const updateform=reactive({
      userId:store.$state.userId,
      modifyById:store.$state.userId,
      modifyByName:store.$state.userNickname,
      createById:'',
      createByName:'',
      createTime:'',
      goodsId:'',
      goodsName:'',
      goodsMade:'',
      goodsDay:'',
      goodsItem:'',
      goodsCompany:'',
      goodsImage:'',
      dialogupdate:false
    })
    //导出
    const exportform=reactive({
      ExportdialogFormVisible:false,
      num:1,
      userId:''
    })


    const handleExport=(userId:any)=>{
      exportform.ExportdialogFormVisible=true
      exportform.userId=userId
    }

    const ExportData=()=>{
      location.href='http://localhost:11836/FarmApp/DownloadExcel?userId='+exportform.userId+'&num='+exportform.num;
      exportform.ExportdialogFormVisible=false;
      exportform.num=1; 
      exportform.userId=''
    }
    

    //非空验证
    const rules = reactive({
        goodsName: [
    { required: true, message: '请填写商品名称', trigger: 'blur' },
  ],
  goodsMade: [
    { required: true, message: '请填写生产批次', trigger: 'blur' },
  ],
  goodsDay: [
    { required: true, message: '请填写保质期', trigger: 'blur' },
  ],
  goodsItem: [
    { required: true, message: '请填写生产许可证号', trigger: 'blur' },
  ],
  goodsCompany: [
    { required: true, message: '请填写生产企业', trigger: 'blur' },
  ],
  goodsImage: [
    { required: true, message: '请填写封面图', trigger: 'blur' },
  ],
    })
    //商品列表
    const goods=ref([])
    const getGoods=()=>{
        axios.get('http://localhost:11836/FarmApp/GetGoods',{
            params:{
                userId:form.userId,
                pageIndex:form.pageIndex,
                pageSize:form.pageSize
            }
        })
        .then(res=>{
            goods.value=res.data.list
            form.recordCount=res.data.recordCount
            form.pageCount=res.data.pageCount
            console.log(res.data)
        })
    }

    onMounted(()=>{
        getGoods()
    })

    //验证
    const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      goodsAdd()
    } else {
      console.log('error submit!', fields)
    }
  })
}
    //商品添加
    const goodsAdd=()=>{
      console.log(form)
        axios.post('http://localhost:11836/FarmApp/GoodsAdd',form)
        .then(res=>{
            if(res.data>0)
            {
                ElMessage.success('添加成功')
                form.dialogFormVisible=false
                getGoods()
            }
            else if(res.data==-1)
            {
                ElMessage.error('商品名称重复')
            }
            else
            {
                ElMessage.error('添加失败')
            }
            
        })
    }
    //反填
    const findGoods=()=>{
        axios.get('http://localhost:11836/FarmApp/FindGoods',{
            params:{
                goodsId:updateform.goodsId
            }
        })
        .then(res=>{
          updateform.createById=res.data.createById
          updateform.createByName=res.data.createByName
            updateform.createTime=res.data.createTime
            updateform.goodsId=res.data.goodsId
            updateform.goodsName=res.data.goodsName
            updateform.goodsMade=res.data.goodsMade
            updateform.goodsDay=res.data.goodsDay
            updateform.goodsItem=res.data.goodsItem
            updateform.goodsCompany=res.data.goodsCompany
            updateform.goodsImage=res.data.goodsImage
            console.log(res.data)
        })
    }

    //修改
    const goodsUpdate=async (formEl: FormInstance | undefined)=>{
        if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
        axios.post('http://localhost:11836/FarmApp/UpDateGoods',updateform)
        .then(res=>{
            if(res.data>0)
            {
                ElMessage.success('修改成功')
                updateform.dialogupdate=false
                getGoods()
            }
            else if(res.data==-1)
            {
                ElMessage.error('商品名称重复')
            }
            else
            {
                ElMessage.error('修改失败')
            }
            console.log(res.data)
        })
    } else {
      console.log('error submit!', fields)
    }
  })
       
    }
  




    const handleAvatarSuccess = (url:any) => {
  form.goodsImage="http://localhost:11836"+url
  updateform.goodsImage="http://localhost:11836"+url
}

const beforeAvatarUpload= (rawFile:any) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}


//弹出修改框
const handleEdit = (goodsId: any) => {
    updateform.goodsId=goodsId
    updateform.dialogupdate=true
    findGoods() 
}
//删除
const handleDelete = ( row: any) => {
  let array:any=[]
  array.push(row)
  ElMessageBox.confirm(
    '确定要删除吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      axios.post('http://localhost:11836/FarmApp/DelRangeGoods',array)
  .then(res=>{
    if(res.data>0)
    {
      ElMessage.success('删除成功')
      getGoods()
    }
    else
    {
      ElMessage.error('删除失败') 
    }
  })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })


}

const handleSelectionChange = (val: any) => {
   form.selectArray=val
}

//批量删除
const del = ( row: any) => {

ElMessageBox.confirm(
  '确定要删除吗?',
  '警告',
  {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }
)
  .then(() => {
    axios.post('http://localhost:11836/FarmApp/DelRangeGoods',form.selectArray)
.then(res=>{
  if(res.data>0)
  {
    ElMessage.success('删除成功')
    getGoods()
  }
  else
  {
    ElMessage.error('删除失败') 
  }
})
  })
  .catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消',
    })
  })


}
//分页
const handleSizeChange = (val: number) => {
  form.pageSize=val
  getGoods()
}
const handleCurrentChange = (val: number) => {
  form.pageIndex=val
  getGoods()  
}

    </script>
    
    